package wei.xinya.myid;

import android.util.Log;

import org.json.JSONObject;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

public class NoticeUtil {

    public static void sendWeiXin(String message) {
        HttpURLConnection connection;
        try {
            URL url = new URL("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=881d5181-4ea0-49b8-bc77-d1ffd889d99c");
            connection = (HttpURLConnection) url.openConnection();
            connection.setConnectTimeout(3000);
            connection.setReadTimeout(3000);
            connection.setRequestProperty("Content-Type", "application/json");

            //设置请求方式 GET / POST 一定要大写
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(false);
            connection.connect();

            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            JSONObject paramJson = new JSONObject();
            paramJson.put("msgtype", "text");

            JSONObject textJson = new JSONObject();
            textJson.put("content", message);
            paramJson.put("text", textJson);

            dos.writeBytes(paramJson.toString());

            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                throw new IOException("HTTP error code" + responseCode);
            }
            String result = getStringByStream(connection.getInputStream());
            if (result == null) {
                Log.d("Fail", "失败了");
            } else {
                Log.d("succuss", "成功了 ");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static String getStringByStream(InputStream inputStream) {
        Reader reader;
        try {
            reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            char[] rawBuffer = new char[512];
            StringBuilder buffer = new StringBuilder();
            int length;
            while ((length = reader.read(rawBuffer)) != -1) {
                buffer.append(rawBuffer, 0, length);
            }
            return buffer.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
